\section{Code for problem 3}
\label{code3}
\small
\begin{verbatim}
# This function generates a sample of random variables 
# with density g of size N for a value of theta.
# The output contains to elements:
#   'ys' are the N accepted values.
#   'rejected' are the rejected values.
generateWithDensityG <- function(theta, N)
{
  # A list for accepted values
  ys <- c()
  # A list for rejected values
  rejected <- c()

  # We keep going until we have N accepted values.
  while(length(ys) < N)
  {
    # We generate x with Unif(-1, 1)
    x <- runif(1, -1, 1)
    # We generate u with Unif(0, 1)
    u <- runif(1)

    # We reject if the acceptance criteria isn't met
    if(u > exp(theta*(x-1))) 
    {
      # We keep the rejected values.
      rejected <- c(rejected, x)
    }
    # We accept if the acceptance criteria is met
    else
    {
      # We keep the accepted value.
      ys <- c(ys, x)
    }
  }

  # We create the result such that it contains 
  # both the accepted and rejected values
  result <- c()
  result$ys <- ys
  result$rejected <- rejected

  return(result)
}

# The size of the sample of accepted values that we want to generate.
N <- 10000

# Generates values with lambda = 1.
sample1 <- generateWithDensityG(1, N)
# Generates values with lambda = 10.
sample10 <- generateWithDensityG(10, N)

# We plot the histograms of the values.
par(mfrow = c(2, 1))
hist(sample1$ys, main = 'Lambda = 1')
hist(sample10$ys, main = 'Lambda = 10')

# We calculates the proportion of values accepted.
length(sample1$ys)/(length(sample1$ys)+length(sample1$rejected))
length(sample10$ys)/(length(sample10$ys)+length(sample10$rejected))

# We calculates the mean of accepted and rejected values for lambda = 1.
mean(sample1$ys)
mean(sample1$rejected)

# We calculates the mean of accepted and rejected values for lambda = 10.
mean(sample10$ys)
mean(sample10$rejected)
\end{verbatim}

\newpage 
